<template>
  <div>
    <el-form @submit.native.prevent :inline="true">
      <el-form-item label="放款时间">
        <el-date-picker
          v-model="startDate"
          placeholder="开始日期"
          type="date"
          value-format="yyyy-MM-dd"
          style="width: 140px"
        ></el-date-picker>
        <span class="px-1">至</span>
        <el-date-picker
          v-model="endDate"
          placeholder="截止日期"
          type="date"
          value-format="yyyy-MM-dd"
          style="width: 140px"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="getData()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-document-checked"
          class="btn-long"
          @click="handleConfirm"
        >
          上报
        </el-button>
        <el-button
          icon="el-icon-download"
          class="btn-long"
          :loading="downloading"
          @click="handleDownload"
        >
          下载
        </el-button>
      </el-form-item>
    </el-form>

    <c-table
      v-loading="loading"
      border
      class="table-sm"
      ref="multipleTable"
      name="table"
      row-key="customer_related_id"
      :columns="tableColumns"
      :data="tableData"
      @selection-change="handleSelectionChange"
    ></c-table>

    <div class="query-pagination">
      <div>
        <el-checkbox
          v-model="allChecked"
          label="全选所有页"
          :disabled="loading"
          @change="handleSelectAll"
        ></el-checkbox>
      </div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="pageParams.index"
        :page-size="pageParams.size"
        :total="tableCount"
        @current-change="getPageData"
      ></el-pagination>
    </div>

    <el-dialog
      title="报表报送"
      :visible.sync="confirmVisible"
      :close-on-click-modal="false"
      append-to-body
      width="430px"
    >
      <div class="row mb-2">
        <div class="col-4 text-right text-muted">当前上报月份：</div>
        <div class="col-8">{{ currentDate.year }}年{{ currentDate.month }}月</div>
      </div>
      <div class="row mb-2">
        <div class="col-4 text-right text-muted">已选项目数量：</div>
        <div class="col-8">{{ selectLen }} 个</div>
      </div>
      <div class="row mb-2">
        <div class="col-4 text-right text-muted">银行放款总额：</div>
        <div class="col-8">{{ totalFunds }} 万元</div>
      </div>
      <div class="row mt-5">
        <div class="col-4"></div>
        <div class="col-8">
          <el-button type="primary" class="btn-long" :loading="loading" @click="handleSubmit">
            上 报
          </el-button>
          <el-button :disabled="loading" @click="confirmVisible = false">取 消</el-button>
        </div>
      </div>
    </el-dialog>

    <province-edit-dialog
      :form-data="editRow"
      :visible.sync="editVisible"
      @success="getData"
    ></province-edit-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { strip } from '@vimi/utils-tool'
import { tableColumns, fields, dataAdapter } from './mixins'

import { jsonExport, getCurrentDate } from '@/credit/views/city/reportCity/reportMixins'
import ProvinceEditDialog from '@/credit/views/city/reportCity/province/guarantee/EditDialog'

export default {
  components: {
    ProvinceEditDialog,
  },
  props: {
    reportId: String,
  },
  data() {
    return {
      loading: false,
      params: {
        'gua_type.in': '1,2,3,4',
      },
      pageParams: {
        index: 1,
        size: 15,
        isBIQuery: 1,
      },
      order: {
        load_date: 'desc',
      },
      tableName: 'market_project',
      tableCount: 0,
      tableData: [],
      allData: [],
      tableColumns: [
        {
          attrs: {
            label: '选择',
            type: 'selection',
            align: 'center',
            width: 55,
            reserveSelection: true,
          },
        },
        ...tableColumns,
        {
          attrs: { label: '操作', align: 'center', fixed: 'right' },
          operations: [{ content: '修改', icon: 'fa fa-edit', event: this.handleEdit }],
        },
      ],

      // 时间选择
      startDate: '',
      endDate: '',

      // 选择
      multipleSelection: [],
      allChecked: false,

      // 上报
      confirmVisible: false,
      totalFunds: 0,

      // 编辑
      editVisible: false,
      editRow: {},

      // 下载
      downloading: false,
    }
  },
  computed: {
    ...mapGetters(['user', 'clientId']),
    selectLen() {
      return this.multipleSelection.length
    },
    currentDate() {
      return getCurrentDate()
    },
  },
  watch: {},
  created() {
    this.initParams()
  },
  mounted() {},
  methods: {
    initParams() {
      this.params['service_id.eq'] = this.clientId
      this.params['is_report_sd.eq'] = 0
      this.params.fields = fields
      this.getData()
    },

    getParams() {
      const params = {
        ...this.params,
      }
      params['load_date.gte'] = this.startDate || ''
      params['load_date.lte'] = this.endDate ? `${this.endDate} 23:59:59` : ''
      return params
    },

    async getData() {
      this.loading = true
      const [res] = await this.fetchData(this.getParams())
      this.loading = false

      this.allData = ((res && res.data) || []).map(dataAdapter)
      this.tableCount = this.allData.length
      this.totalPages = Math.ceil(this.tableCount / this.pageParams.size)

      this.getPageData(1)
    },

    fetchData(params) {
      return this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, params, this.order)
      )
    },

    getPageData(index) {
      this.tableData = []
      this.pageParams.index = index
      const start = (index - 1) * this.pageParams.size
      const end = this.totalPages <= index ? this.allData.length : start + this.pageParams.size
      for (let i = start; i < end; i++) {
        this.tableData.push(this.allData[i])
      }
    },

    handleSelectionChange(val) {
      this.multipleSelection = val
      this.allChecked = this.selectLen === this.allData.length
    },

    // 全选
    handleSelectAll(val) {
      const $tableRef = this.$refs.multipleTable.$refs.table
      if (!$tableRef) return

      if (val) {
        $tableRef.store.states.selection = this.allData.slice()
        $tableRef.$emit('selection-change', this.allData.slice())
        $tableRef.store.updateAllSelected()
      } else {
        $tableRef.clearSelection()
      }
    },

    handleConfirm() {
      if (!this.selectLen) {
        return this.$message.error(this.tableData.length ? '请先选择上报项目' : '暂无可上报的项目')
      }
      this.confirmVisible = true
    },

    async handleSubmit() {
      // 银行放款总金额
      this.totalFunds = 0
      for (const item of this.multipleSelection) {
        this.totalFunds += item.confirm_reply_funds
      }
      this.totalFunds = strip(this.totalFunds)

      const {
        user: { userId, realName, phoneNumber },
        clientId,
        currentDate,
      } = this
      const masterTable = 'report_month'
      const slaveTable = 'report_month_detail_county'

      if (this.reportId) {
        return this.$message.error(
          `${currentDate.year}年${currentDate.month}月省担报表已报送，不能再上报！`
        )
        // 以下逻辑为追加上报
        // this.loading = true
        // return this.$api.addBatch(
        //   this.$serviceName,
        //   slaveTable,
        //   this.multipleSelection.map(it => ({
        //     report_month_id: reportId,
        //     customer_related_id: it.customer_related_id,
        //     submit_person: userId,
        //     submit_person_name: realName,
        //     update_person: userId
        //   }))
        // ).then(res => {
        //   this.onSuccess(res)
        // }).finally(() => {
        //   this.loading = false
        // })
      }

      const masterData = {
        avg_gua_rate: 0,
        avg_loan_rate: 0,
        in_gua_multiple: 1,
        new_gua_multiple: 1,
        report_type: 5,
        phone_number: phoneNumber,
        service_id: clientId,
        submit_person: userId,
        submit_person_name: realName,
        update_person: userId,
        report_name: '',
        year_number: currentDate.year,
        month_number: currentDate.month,
      }
      const slaveData = this.multipleSelection.map(it => ({
        customer_related_id: it.customer_related_id,
        submit_person: userId,
        submit_person_name: realName,
        update_person: userId,
      }))
      const formData = {
        masterTableInfo: JSON.stringify(masterData),
        masterTableName: masterTable,
        slaveTableInfo: JSON.stringify(slaveData),
        slaveTableName: slaveTable,
      }

      // 关联添加
      this.loading = true
      this.$api
        .relatedBatch(this.$serviceName, formData)
        .then(res => {
          this.onSuccess(res)
        })
        .catch(() => {
          this.$message.error('上报失败，请重试！')
        })
        .finally(() => {
          this.loading = false
        })
    },

    onSuccess(res) {
      this.pageParams.index = 1
      this.getData()
      this.$message.success('上报成功！')
      this.confirmVisible = false
      this.$emit('success', res)
    },

    async handleDownload() {
      if (!this.selectLen) {
        return this.$message.error(this.tableData.length ? '请先选择项目' : '暂无可下载的项目')
      }

      this.downloading = true
      jsonExport({
        columns: this.tableColumns,
        data: this.multipleSelection,
        adapter: dataAdapter,
        filename: '省担报表',
      }).finally(() => {
        this.downloading = false
      })
    },

    handleEdit(row) {
      this.editRow = { ...row }
      this.editVisible = true
    },
  },
}
</script>

<style lang="scss" scoped></style>
